package com.stackfarm.fvcommon.exception;

import com.stackfarm.fvcommon.constant.ReturnCode;
import com.stackfarm.fvcommon.result.ResultBean;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ErrorHandler {
    @ExceptionHandler(Exception.class)
    public ResultBean<?> handleExption(Exception e) {
        ResultBean<Void> resultBean = new ResultBean<>();
        resultBean.setTimestamp(System.currentTimeMillis());
        resultBean.setCode(ReturnCode.INVALID_CODE);
        resultBean.setData(null);
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            resultBean.setMsg(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage() + "");
            return resultBean;
        }
        if (e instanceof java.lang.NumberFormatException) {
            resultBean.setMsg("请输入符合类型的数值");
            return resultBean;
        }
        resultBean.setMsg("未知错误");
        resultBean.setCode(ReturnCode.UNKNOWN_ERROR);
        return resultBean;
    }
}
